package com.jwgf.smarowindingmachine_unity.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jwgf.adapter.ItemViewDelegate;
import com.jwgf.adapter.MultiItemTypeAdapter;
import com.jwgf.adapter.RecyclerViewHolder;
import com.jwgf.smarowindingmachine_unity.R;

import java.util.ArrayList;
import java.util.List;

public class CustomSelectedDialog extends DialogFragment {
    public static final String ITEMS = "items";
    public static final String GROUP_COUNT = "group_count";
    public static final String SPINDLE_COUNT = "spindle_count";
    private Callback callback;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        List<String> list = getArguments().getStringArrayList(ITEMS);

        RecyclerView recyclerView = new RecyclerView(getActivity());
        MultiItemTypeAdapter<String> rvAdapter = new MultiItemTypeAdapter<String>(getActivity(), list);
        rvAdapter.addItemViewDelegate(new ButtonDelegate());
        rvAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (callback != null)
                    callback.onItemSelected(rvAdapter.getDatas().get(position), position);
                dismiss();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 9);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(rvAdapter);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(getResources().getString(R.string.select));
        builder.setView(recyclerView);
        return builder.create();
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    interface Callback {
        void onItemSelected(String text, int index);
    }

    class ButtonDelegate implements ItemViewDelegate {

        @Override
        public int getItemViewLayoutId() {
            return R.layout.navigation_button;
        }

        @Override
        public boolean isForViewType(Object item, int position) {
            return item instanceof String;
        }

        @Override
        public void bindView(RecyclerViewHolder holder, Object o, int position) {
            String attr = (String) o;
            holder.setText(R.id.btn, attr);
        }
    }
}
